<template>
    <div class="fillContain">
        <head-top></head-top>
        <div class="table_container">
            <el-form :inline="true" size="mini" :label-position="labelPosition" ref="reportForm">
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="报表名称">
                            <el-input v-model="report.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="数据源">
                            <el-select v-model="report.dsId" placeholder="请选择数据源">
                                <el-option label="数据源1-mysql" value="102"></el-option>
                                <el-option label="数据源2-皮皮陈Mysql" value="52"></el-option>
                                <el-option label="数据源2-oracle" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="状态">
                            <el-select v-model="report.status" placeholder="请选择状态">
                                <el-option label="禁用" value="0"></el-option>
                                <el-option label="启用" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <textarea ref="textarea"></textarea>

            </el-form>

            <el-row style="margin-top: 1%">
                <el-col :span="24" style="text-align: center">
                    <el-button size="mini" round type="warning" icon="el-icon-caret-right" @click="executeSql">执行sql
                    </el-button>
                    <el-button size="mini" round type="primary" icon="el-icon-view" @click="previewReport">
                        预览报表
                    </el-button>
                    <el-button size="mini" round type="primary" icon="el-icon-view" @click="save">保存报表</el-button>
                    <el-button size="mini" round type="primary" icon="el-icon-view" @click="test">测试</el-button>

                </el-col>
            </el-row>
            <el-row v-if="hasMetaColumn">
                <el-col><label>元数据列配置</label></el-col>
            </el-row>
            <el-row v-if="hasMetaColumn">
                <hr style="height:1px;border:none;border-top:1px solid #555555;"/>
            </el-row>

            <el-row v-if="hasMetaColumn">
                <el-col :span="8">
                    <el-row v-if="hasMetaColumn">
                        <el-col :span="8"><label>列名</label></el-col>
                        <el-col :span="11"><label>标题</label></el-col>
                    </el-row>
                    <el-row v-for="column in metaColumnsList" :key="column.id">
                        <el-col :span="8">
                            <el-input v-model="column.name" placeholder="请输入列名" size="mini"></el-input>
                        </el-col>
                        <el-col :span="11">
                            <el-input v-model="column.text" placeholder="请输入标题" size="mini"></el-input>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col :span="14">
                    <el-tree
                            :data="tableHeaderTreeData"
                            node-key="id"
                            default-expand-all
                            draggable
                            @node-drop="handleDrop">
                    </el-tree>
                </el-col>
            </el-row>

        </div>


        <el-dialog
                title="报表预览"
                :visible.sync="dialogPreviewReport"
                width="80%">
            <el-table>
                <table-header v-bind:tableHeaderChildData="tableHeaderTreeDataCopy"></table-header>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogPreviewReport = false">取 消</el-button>
                 <el-button type="primary" @click="dialogPreviewReport = false">确 定</el-button>
             </span>
        </el-dialog>
    </div>

</template>

<script>
    /* eslint-disable no-console,no-undef */
    //import {axios} from '../utils/'
    import {execSqlText, getReoprtInfo, addReport, previewReport} from '@/api/getData'
    import HeadTop from '@/views/main-components/HeadTop.vue'
    import TableHeaderTree from '@/views/report/TableHeaderTree.vue'
    import ReportPreview from '@/views/report/ReportPreview.vue'
    import TableHeader from '@/views/report/TableHeader.vue'

    import {getStore, setStore} from '@/utils/storage';

    import CodeMirror from 'codemirror'
    import 'codemirror/addon/lint/lint.css'
    import 'codemirror/lib/codemirror.css'
    import 'codemirror/theme/rubyblue.css'

    import 'codemirror/mode/javascript/javascript'
    import 'codemirror/addon/lint/lint'
    import 'codemirror/addon/hint/sql-hint'

    export default {
        data() {
            return {
                report: {
                    id: '',
                    categoryId: 1,
                    name: '',//报表名称
                    dsId: '',//数据源
                    sqlText: '',//sql语句
                    metaColumns: '',//元数据列
                    queryParams: '',//查询参数
                    options: '',//配置选项
                    status: '',//状态
                },
                previewReportData: {
                    comment: '',
                    formHtmlText: '',
                    id: '',
                    name: '',
                    nonStatColumHtmlText: '',
                    statColumHtmlText: '',
                    uid: ''
                },
                labelPosition: 'left',
                sqlEditor: false,
                hasMetaColumn: false,
                metaColumnsList: "",
                tableHeaderTreeData: [],
                tableHeaderTreeDataCopy:[],
                dialogPreviewReport: false
            };
        },
        mounted() {
            //设置sql样式
            this.sqlEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
                mode: 'text/x-mysql',
                theme: 'rubyblue',
                indentWithTabs: true,
                smartIndent: true,
                lineNumbers: true,
                matchBrackets: true,
                autofocus: true,
                width: '100%',
                extraKeys: {
                    "F1": function (cm) {
                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                    },
                    "Esc": function (cm) {
                        if (cm.getOption("fullScreen")) {
                            cm.setOption("fullScreen", false);
                        }
                    }
                }
            });

        },
        computed: {

        },
        components: {
            HeadTop,
            TableHeaderTree,
            ReportPreview,
            TableHeader
        },
        methods: {
            //查询报表
            async query() {
                let reply = await getReoprtInfo();
                if (reply == undefined || reply == 'error') {
                    this.$notify.error({
                        title: '错误',
                        message: '服务器异常或无响应，请联系相关人员！'
                    });
                }
            },
            //执行sql
            async executeSql() {
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                let param = {
                    sqlText: this.sqlEditor.getValue(),
                    dsId: this.report.dsId,
                    dataRange: '',
                    queryParams: null
                };
                this.report.sqlText = this.sqlEditor.getValue();
                let reply = await execSqlText(param);
                loading.close();
                if (reply.code == 500) {
                    this.$notify.error({
                        title: '错误',
                        message: '服务器异常或无响应，请联系相关人员！'
                    });
                } else {
                    this.hasMetaColumn = true;
                    if (this.metaColumnsList.length < 1) {
                        this.metaColumnsList = reply.data;
                    } else {
                        //如果列表中存在旧的列则需要替换相同的列并增加新列
                        var oldRowMap = {};
                        for (let i = 0; i < this.metaColumnsList.length; i++) {
                            var name = this.metaColumnsList[i].name;
                            oldRowMap[name] = this.metaColumnsList[i];
                        }

                        for (let i = 0; i < reply.data.length; i++) {
                            let name = reply.data[i].name;
                            if (oldRowMap[name]) {
                                oldRowMap[name].dataType = reply.data[i].dataType;
                                oldRowMap[name].width = reply.data[i].width;
                                reply.data[i] = oldRowMap[name];
                            }
                        }
                        this.metaColumnsList = reply.data;
                    }
                    let i = 11;
                    let arr = [];
                    let fatherTree = [];
                    let fatherNode = {};
                    fatherNode.id = 1;
                    fatherNode.label = "请调整表头"
                    for (let data of this.metaColumnsList) {
                        i++;
                        data.id = i;
                        data.label = data.text;
                        arr.push(data);
                    }
                    fatherNode.children = arr;
                    fatherTree.push(fatherNode);
                    this.tableHeaderTreeData = fatherTree;
                }

            },
            previewReport() {
                this.dialogPreviewReport = true;
                this.tableHeaderTreeDataCopy = this.$store.state.tableHeader;
            },
            async save() {
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                this.report.options = JSON.stringify({
                        layout: this.report.layout,
                        statColumnLayout: this.report.statColumnLayout
                    }
                );
                let metaColumnStr = JSON.stringify(this.metaColumnsList);
                this.report.metaColumns = metaColumnStr;
                let reply = await addReport(this.report);
                if (reply.code == 200) {
                    this.report.id = reply.data;
                    loading.close();
                    this.$notify.success({
                        title: '',
                        message: '成功！'
                    });
                } else {
                    loading.close();
                }
            },
            test: function () {

            },
            handleDrop(draggingNode, dropNode, dropType, ev) {
                this.$store.commit('saveTableHeader', this.tableHeaderTreeData);
            },

        }
    }
</script>

<style scoped>

</style>